package com.example.ykbboom.universitytransportation.Activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.example.ykbboom.universitytransportation.R;
import com.example.ykbboom.universitytransportation.Util.LogUtil;
import com.example.ykbboom.universitytransportation.Util.SharedPrefUtil;
import com.example.ykbboom.universitytransportation.Util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author ykbboom
 * @email ykbpro@whut.edu.cn
 * @time 2017-2-27 14:44:18
 * 功能: 选择地点
*/
public class ChoosePlaceActivity extends BaseActivity implements Inputtips.InputtipsListener,
        GeocodeSearch.OnGeocodeSearchListener {
    private static final String TAG = "ChoosePlaceActivity";
    private String LOCAL_CITY;//此处应根据当前定位城市设置,数据需进行缓存
    private Toolbar mtoolbar;
    private TextWatcher textWatcher;
    private Button deleteReqBtn;
    private AutoCompleteTextView requestText;
    private ListView inputList;
    private Intent intent;
    private Button completeReqBtn;
    private GeocodeSearch geocodeSearch;
    private ProgressDialog progressDialog;
    private String place;//用户选择的地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_place);
        intent = new Intent(ChoosePlaceActivity.this,PublishRequestActivity.class);
        initWatcher();
        initView();

    }

    @Override
    public void initView() {
        mtoolbar = (Toolbar) findViewById(R.id.toolbar_choose_place);
        setSupportActionBar(mtoolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        requestText = (AutoCompleteTextView) findViewById(R.id.request_edit);
        requestText.addTextChangedListener(textWatcher);//设置EditText监控事件
        inputList = (ListView) findViewById(R.id.input_list);
        deleteReqBtn = (Button) findViewById(R.id.delete_req_btn);
        completeReqBtn = (Button) findViewById(R.id.complete_req_btn);
        completeReqBtn.setOnClickListener(this);
        deleteReqBtn.setOnClickListener(this);
        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        progressDialog = new ProgressDialog(this);
        LOCAL_CITY = SharedPrefUtil.getUserCity();
    }
    /**
     * 显示进度框
     * */
    public void showDialog() {
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(true);
        progressDialog.setMessage("正在获取地址");
        progressDialog.show();
    }
    /**
     * 消失
     * */
    public void dismissDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.delete_req_btn:
                requestText.setText("");
                break;
            case R.id.complete_req_btn:
                place = requestText.getEditableText().toString();
                getLatlon(requestText.getEditableText().toString());
        }
    }
    private void initWatcher(){
        textWatcher = new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString().trim();
                InputtipsQuery inputQuery = new InputtipsQuery(newText, LOCAL_CITY);
                inputQuery.setCityLimit(true);
                Inputtips inputTips = new Inputtips(ChoosePlaceActivity.this, inputQuery);
                inputTips.setInputtipsListener(ChoosePlaceActivity.this);
                inputTips.requestInputtipsAsyn();
            }
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
            public void afterTextChanged(Editable s) {
                if(s.toString().length()>0){
                    deleteReqBtn.setVisibility(View.VISIBLE);
                    completeReqBtn.setVisibility(View.VISIBLE);

                }else{
                    deleteReqBtn.setVisibility(View.INVISIBLE);
                    completeReqBtn.setVisibility(View.INVISIBLE);
                }
            }
        };
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }
    /**
    *此方法必须重写
    **/
    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            final List<HashMap<String, String>> listString = new ArrayList<HashMap<String, String>>();
            for (int i = 0; i < tipList.size(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("name", tipList.get(i).getName());
                map.put("address", tipList.get(i).getDistrict());
                listString.add(map);
            }
            SimpleAdapter aAdapter = new SimpleAdapter(getApplicationContext(), listString, R.layout.place_item_layout,
                    new String[] {"name","address"}, new int[] {R.id.poi_field_id, R.id.poi_value_id});

            inputList.setAdapter(aAdapter);
            inputList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    HashMap<String,String>hashMap = listString.get(position);
                    place = hashMap.get("name");
                    getLatlon(place);
                }
            });
            aAdapter.notifyDataSetChanged();

        } else {
        }

    }
    /**
     * 地理编码
     */
    public void getLatlon(final String place) {
        showDialog();

        GeocodeQuery query = new GeocodeQuery(place,LOCAL_CITY);// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
        geocodeSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
    }
    /**
     * 回调解析逆编码结果
     * */
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

    }
    /**
     * 回调解析编码结果
     * */
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
        dismissDialog();
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getGeocodeAddressList() != null
                    && result.getGeocodeAddressList().size() > 0) {
                GeocodeAddress address = result.getGeocodeAddressList().get(0);
//                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
//                        AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));
//                geoMarker.setPosition(AMapUtil.convertToLatLng(address
//                        .getLatLonPoint()));
                LogUtil.i(TAG,"经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
                        + address.getFormatAddress());
                intent.putExtra("place",place);
                intent.putExtra("latlong",address.getLatLonPoint().toString());
                setResult(RESULT_OK,intent);
                finish();
            } else {
                ToastUtil.showToast(ChoosePlaceActivity.this, "无法解析该地址");
            }
        } else {
            ToastUtil.showToast(ChoosePlaceActivity.this, String.valueOf(rCode));
        }
    }
}

